package com.cfr.utils;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;


public class FileUtils {

	protected static Logger logger = Logger.getLogger(FileUtils.class);


	/**
	 * @param string
	 * @param orgDoc
	 * @throws FileNotFoundException
	 * @throws TransformerException
	 */

	public static File saveXMLtoFile(String name, Document document) {
		File newXML = null;
		TransformerFactory transFactory = TransformerFactory.newInstance();
		try {
			Transformer transformer = transFactory.newTransformer();
			DOMSource source = new DOMSource(document);
			newXML = new File(name + ".xml");
			FileOutputStream os = new FileOutputStream(newXML);
			StreamResult result = new StreamResult(os);
			transformer.transform(source, result);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return newXML;
	}

	public static File storeFile(String filename, InputStream inputStream) {

		File file = new File(filename);
		try {
			OutputStream out = new FileOutputStream(file);
			byte buf[] = new byte[1024];
			int len;
			while ((len = inputStream.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
			out.flush();
			out.close();
			inputStream.close();
			logger.info(file.getName() + " is created...");
		} catch (FileNotFoundException e) {
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
		return file;
	}
}
